//
//  LoadingPlugin.swift
//  Networking
//
//  Created by 许必成 on 2020/7/22.
//  Copyright © 2020年 东信北邮信息技术有限公司. All rights reserved.
//

import UIKit
import Moya
import HandyJSON

let LoadingPlugin = NetworkActivityPlugin { (type, target) in
    switch type {
    case .began:
        print("began")
    case .ended:
        print("ended")
    }
}

let timeoutClosure = {(endpoint: Endpoint, closure: MoyaProvider<EBAPI>.RequestResultClosure) -> Void in
    
    if var urlRequest = try? endpoint.urlRequest() {
        urlRequest.timeoutInterval = 20
        closure(.success(urlRequest))
    } else {
        closure(.failure(MoyaError.requestMapping(endpoint.url)))
    }
}

let ApiProvider = MoyaProvider<EBAPI>(requestClosure: timeoutClosure)

let ApiLoadingProvider = MoyaProvider<EBAPI>(requestClosure: timeoutClosure, plugins: [LoadingPlugin])


enum EBAPI {

// MARK: 0.公共接口
    
    /// 用户登录接口
    /// username：用户名
    /// passwork：密码
    case userLogin(username: String, password: String ,captcha_id:String , captcha:String)
    
    //防疫人员, 告警列表
    case getAlarmList(alarmName: String?, alarmType: String?, alarmStatus: String?)
    
    //人员详情
    case getPersonInfo(uid: String, name: String)
    

    //AED设备列表
    case getAEDList(name: String?, seriNo: String?)
    
    // 修改头像
    case uploadAvatar(img: UIImage)
    
    // AED设备状态切换-急救人员端
    case aedTogglestatus(aed_id:Int , aed_status:String)
    
    //修改密码
    case adminPwd(old_pwd:String , new_pwd:String ,confirm_pwd:String )
    
    //修改昵称
    case updateCurrent(account_name:String )
    
    //急救指导视频列表与搜索-急救人员端
    case getGuideList(name:String?, type:String ,page:String , pageSize:String)
    
    case getFAQ
    
    case getMaintainList(page: String, pageSize: String)
    
    case recognitFace(base64Str: String)
    
    /// 短信验证码
    case smscaptcha(phone_num:String)
    
    /// 图片验证码
    case captcha
    /// 重置密码
    case modPwdByCaptcha(phone_num:String , captcha:String , password:String)
}

extension EBAPI: TargetType {

    var baseURL: URL { return URL(string: BaseURL)! }
    
    var path: String {
        switch self {
                       
        case .userLogin(_,_,_,_):
            return "/api/auth/login"
        
        case .getAlarmList(_, _, _):
            return "/api/alarm"
        
        case .getPersonInfo(let uid, _):
            return "/api/participant/\(uid)"
            
        case .getAEDList(_, _):
            return "/api/aed"

        case .uploadAvatar(_):
            return "/api/upload/avatar"
        case .aedTogglestatus(_,_):
            return "/api/aed/togglestatus"
        case .adminPwd(_,_,_):
            return "/api/adminPwd"
        case .updateCurrent(_):
            return "/api/updateCurrent"
        case .getGuideList(_,_,_,_ ):
            return "/api/faguide"
        case .getFAQ:
            return "/api/faq"
        case .getMaintainList(_, _):
            return "/api/admin"
        
        case .recognitFace(_):
            return "/api/participant/recognit"
        case .smscaptcha(_):
            return "/api/smscaptcha"
        case .captcha:
            return "/api/captcha"
        case .modPwdByCaptcha:
            return "/api/modPwdByCaptcha"
        }
        
    }
    
    
    var method: Moya.Method {
        
        switch self {
        case .userLogin(_, _,_,_):
            
            return .post
            
        case .uploadAvatar(_):
            
            return .post
            
        case .adminPwd(_,_,_):
            return .post
            
        case .updateCurrent(_):
            return .post
        case .aedTogglestatus(_,_):
            return .post
        
        case .recognitFace:
            return .post
            
        case .modPwdByCaptcha(_,_,_ ):
            return .post
            
        default:
            return .get
        }
                
        
    }
    var task: Task {
        
        var parmeters = [String : Any]()
        
        
        switch self {
        case .userLogin(let username, let password ,let captcha_id,let captcha):
            parmeters["login"] = username
            parmeters["password"] = password
            parmeters["captcha_id"] = captcha_id
            parmeters["captcha"] = captcha
        
        case .getAlarmList(let alarmName, let alarmType, let alarmStatus):
            if let name = alarmName {
                parmeters["parti_name"] = name
            }
            
            if let type = alarmType {
                parmeters["alarm_type"] = type
            }
            
            if let status = alarmStatus {
                parmeters["alarm_status"] = status
            }
                    
        case .getPersonInfo(_, let name):
            parmeters["name"] = name
            
        case .getAEDList(let name, let seriNo):
            if let aedName = name {
                parmeters["aed_name"] = aedName
            }
            
            if let aedSeriNo = seriNo {
                parmeters["aed_serialno"] = aedSeriNo
            }
            
        case .aedTogglestatus(let aed_id , let aed_status):
            parmeters["aed_id"] = aed_id
            parmeters["aed_status"] = aed_status
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .updateCurrent(let account_name):
            parmeters["account_name"] = account_name
            
        case .adminPwd(let old_pwd, let new_pwd, let confirm_pwd):
            
            parmeters["old_pwd"] = old_pwd
            parmeters["new_pwd"] = new_pwd
            parmeters["confirm_pwd"] = confirm_pwd
   
            
        case .uploadAvatar(let img):
            let data:Data = img.jpegData(compressionQuality: 0.9)!
      
            let date:Date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd-HH:mm:ss"
            var dateStr:String = formatter.string(from: date as Date)
            dateStr = dateStr.appendingFormat("-%i.png", 0)
            
            let formData: Moya.MultipartFormData = Moya.MultipartFormData.init(provider: .data(data), name: "file", fileName: dateStr, mimeType: "image/png")
   
            return .uploadMultipart([formData])
        
    
            
        case .getGuideList(let name, let type,  let page, let pageSize):
            if let nm = name {
                parmeters["name"] = nm
            }
            parmeters["type"] = type
            parmeters["page"] = page
            parmeters["pageSize"] = pageSize
            
        case .getFAQ:
            print("=")
            
        case .getMaintainList(let page, let pageSize):
            parmeters["type"] = "4"
            parmeters["page"] = page
            parmeters["pageSize"] = pageSize
            
        case .recognitFace(let imgStr):
            parmeters["image"] = imgStr
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)

        case .smscaptcha(let phone_num):
            parmeters["phone_num"] = phone_num
            return .requestParameters(parameters: parmeters, encoding: URLEncoding.default)
        case .captcha:
            return .requestParameters(parameters: parmeters, encoding: URLEncoding.default)
        case .modPwdByCaptcha( let phone_num,  let captcha,  let password):
            parmeters["phone_num"] = phone_num
            parmeters["captcha"] = captcha
            parmeters["password"] = password
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        }
        print("\(parmeters)")
        return .requestParameters(parameters: parmeters, encoding: URLEncoding.default)
    }
    
    var sampleData: Data { return "".data(using: String.Encoding.utf8)! }
    var headers: [String : String]? {
        
        if let user = GZCurrentUser.shared.currentUser {
            return ["Authorization":user.token, "OS": "ios"]
        }else{
            return ["OS": "ios"]
        }
        
    }
}



